package com.lagou.homeworkzk.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lagou.homeworkzk.model.DataSourceInfo;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.catalina.mapper.Mapper;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class InitApplicationRunner implements ApplicationRunner {
    
    private String zkBaseNode="/hw-datasource";
    // 获取zkClient对象
    private ZkClient zkClient;
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        System.out.println("初始化：InitApplicationRunner");
        //设置自定义的序列化类型,否则会报错！！
        zkClient = new ZkClient("linux121:2181");
        zkClient.setZkSerializer(new ZkStrSerializer());

        //注册监听器，节点数据改变的类型，接收通知后的处理逻辑定义
        zkClient.subscribeDataChanges(zkBaseNode, new IZkDataListener() {
            public void handleDataChange(String path, Object data) throws Exception {
                //修改连接信息后同步变更数据源
                System.out.println(path + " data is changed ,new data " + data);
                ObjectMapper mapper=new ObjectMapper();
                DynamicDatasourceHolder.setDatasource(mapper.readValue(data.toString(),DataSourceInfo.class));
            }

            //数据删除--》节点删除
            public void handleDataDeleted(String path) throws Exception {
                System.out.println(path + " is deleted!!");
            }
        });

        //向zk中写入默认的数据库连接信息
        DataSourceInfo dataSourceInfo = new DataSourceInfo();
        ObjectMapper mapper=new ObjectMapper();
        zkClient.writeData(zkBaseNode,mapper.writeValueAsString(dataSourceInfo));

        //读取默认的连接信息
        final Object o = zkClient.readData(zkBaseNode,true);
        System.out.println(o);
        DynamicDatasourceHolder.setDatasource(mapper.readValue(o.toString(),DataSourceInfo.class));
//        zkClient.close();
    }
}